import router from '@/router'
import axios from 'axios'

// import { MessageBox, Message } from 'element-ui'
import {
	Notify,
	Dialog,
	Toast
} from 'vant';
import store from '@/store'
import {
	getToken
} from '@/utils/auth'

var  LangCode = require('@js/lang/requireCode')  

// import { log } from '@/utils' //paralympic_phase2
let url = process.env.VUE_APP_BASE_API
// process.env.NODE_ENV == 'production' ? 'https://mp2.teamotto.me/paralympic_phase2/api/' :'https://mp2.teamotto.me/paralympic_tea/api';
//	'http://192.168.3.25:8086/api';
// create an axios instance
const service = axios.create({
	baseURL: url, // url = base url + request url
	// withCredentials: true, // send cookies when cross-domain requests
	timeout: 10000 // request timeout,
})
service.methods = ['get', 'post', 'put', 'delete']
// request interceptor
service.interceptors.request.use(
	config => {
		// do something before request is sent
		if (store.getters.token) {
			config.headers['Authorization'] = getToken()
		}
		//config.headers['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8'
		config.headers['Content-Type'] = config.headers['Content-Type'] || 'application/x-www-form-urlencoded;charset=UTF-8'
		// config.headers['Content-Type'] = 'application/json;charset=UTF-8'
		let data = config.data;
		let params = config.params;
	
		if (data) {
			const tyN = typeof(data)
			if (tyN === 'object') {
				const dataN = {}
				for (var key in data) {
					if (data[key] || data[key] === 0) {
						dataN[key] = data[key]
					}
				}
				data = dataN
			}
		}
		if (params) {
			const tyP = typeof(params)
			if (tyP === 'object') {
				const paramsN = {}
				for (var keyN in params) {
					if (params[keyN] || params[keyN] === 0) {
						paramsN[keyN] = params[keyN]
					}
				}
				params = paramsN
			}
		}
		if (data) {
			config.transformRequest = [function(data) {
				const formData = new FormData()
				// debugger
				for (const key of Object.keys(data)) {
					var datas = data[key]
					const ty = typeof(datas)
					if (ty === 'object') {
						datas = JSON.stringify(datas)
					}
					if (datas) {
						formData.append(key, datas)
					}
				}
				return formData
			}]
		}
		config.data = data
		config.params = params
		config.url = config.url + '?t=' + new Date().getTime()
		return config
	},
	error => {
		// do something with request error
		return Promise.reject(error)
	}
)

// response interceptor
service.interceptors.response.use(
	response => {
		console.log('respon',response)
		let res = response.data
		let langCh = window.localStorage.getItem('lang') ==='en'
		try{
			res.msg  = LangCode.default[res.status][langCh?0:1]
				} catch (errs) {
					console.log('LangCode is err ',response.data.msg)
				//alert(response.data.msg)
				}
		if (res.code !== undefined) {
			res.status = res.code === 20000 ? 0 : res.code
		}

		//alert(res.status)
		// if the custom code is not 20000, it is judged as an error.
		if (res.status !== 0 && res.status !== 200) {
			// 50008: Illegal token; 50012: Other clients logged in; 50014: Token expired;
			if ( /*res.status === 2002 ||*/ res.status === 50008 || res.status === 50012 || res.status === 50014 || res.status ===2002) {
				// to re-login
				Dialog.confirm({
					message: 'You have been logged out, you can cancel to stay on this page, or log in again',
					title: 'Confirm logout',
					confirmButtonText: 'Re-Login',
					cancelButtonText: 'Cancel',
					type: 'warning'
				}).then(() => {
					store.dispatch('user/resetToken').then(() => {
						location.reload()
					})
				}).catch(()=>{
					store.dispatch('user/resetToken').then(() => {
						location.reload()
					})
				})
			} else {
				
				Notify({
					message: res.msg || 'Error',
					type: 'warning',
					duration: 2000
				})
				if (res.status === 2020) {
					router.push({
						path: '/'
					})
				}
			}
			return Promise.reject(res)
			// return Promise.reject(new Error(res.message || 'Error'))
		} else {
			if (res.result) {
				if (res.result.list) {
					if (!res.result.list.length) {
						Notify({
							message: 'No data',
							type: 'warning',
							duration: 2000
						})
					}
				}
			}
			return Promise.resolve(res)
		}
	},
	error => {
		//alert(2)
		// console.log('err', error,Notify) // for debug
		
		Notify({
			message: error.message,
			type: 'warning',
			duration: 2 * 1000
		})
		return Promise.reject(error)
	}
)

service.get = function(url = '', options = {}, success, error) {
	options = options ? options : {}
	options.url = url
	options.method = 'get'
	this.ajax(options, success, error)
}
service.delete = function(url = '', options = {}, success, error) {
	options = options ? options : {}
	options.url = url
	options.method = 'delete'
	this.ajax(options, success, error)
}
service.put = function(url = '', options = {}, success, error) {
	options = options ? options : {}
	options.url = url
	options.method = 'put'
	this.ajax(options, success, error)
}

service.post = function(url = '', options = {}, success, error) {
	//console.log(options,success,error)
	options = options ? options : {}
	options.url = url
	options.method = 'post'
	this.ajax(options, success, error)
}
service.formatOpts = function(options) {

	let defaultOpts = {
		url: '',
		method: 'get',
		responseType: 'json',
		responseEncoding: 'utf8',
		headers: {
			'content-type': 'application/x-www-form-urlencoded; charset=utf-8',
		},
		//其它参数
		jsonkey: false, //是否将参数转成 key: '', key为拼接的json字符串
		isloading: true, //默认有加载遮罩
	}

	if (typeof options.headers !== undefined) {
		options.headers = Object.assign({}, defaultOpts.headers, options.headers)
	}
	options = Object.assign({}, defaultOpts, options)
	if (this.methods.indexOf(options.method) == -1) {
		console.log('请求方法有误')
		return false
	}
	if (options.transformRequest && options.data) {
		options.transformRequest = [function(options) {
			let formData = new FormData()
			for (const key of Object.keys(options.data)) {
				formData.append(key, options.data[key])
			}
			return formData
		}]
	}
	return options
}
service.ajax = function(options = {}, success, error) {

	options = this.formatOpts(options)
	if (options.isloading) {
		Toast.loading({
			background: 'rgba(0, 0, 0, .7)',
			text: '加载中'
		})
	}
	if (options.data || options.params) {
		let data = options.params || options.data
		// console.log("asdad",'请不要输入表情符号')
		var reg = /\uD83C[\uDF00-\uDFFF]|\uD83D[\uDC00-\uDE4F]/g //表情正则
		for (var i in data) {
			if (reg.test(i) || reg.test(data[i])) {
				console.log("请不要输入表情符号", '请不要输入表情符号')
				Notify({
					message: '请不要输入表情符号',
					type: 'warning',
					duration: 5 * 1000
				})
				return {
					code: '-1',
					msg: '请不要输入表情符号',
					data: null
				}
			}
		}
	}
	service(options).then((res) => success(res)).catch((err) => error(err))
}

export default service
